﻿using ControlzEx.Standard;
using SuporeSliplampApp.Control;
using SuporeSliplampApp.Models;
using SuporeSliplampApp.Service;
using SuporeSliplampApp.Util;
using SuporeSliplampApp.ViewModels;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using Xceed.Wpf.Toolkit.PropertyGrid.Converters;
using Microsoft.Win32;
using iTextSharp.xmp.impl.xpath;
using Emgu.CV;
using Emgu.Util;
using Emgu.CV.UI;
using Emgu.CV.Structure;
using System.Drawing;
using System.Drawing.Imaging;
using Emgu.CV.CvEnum;
using System.Windows.Media.Media3D;
using PdfSharp.Pdf.Content.Objects;
using SuporeSliplampApp.Base;
using System.Diagnostics;
using System.Windows.Forms;
using Org.BouncyCastle.Asn1;
using System.Security;
using Xceed.Wpf.AvalonDock.Controls;
using System.Web.UI.WebControls;
using System.Runtime.CompilerServices;
using System.Globalization;
using System.Media;

//using OpenCvSharp;
//using OpenCvSharp.Extensions;
//using OcvSize = OpenCvSharp.Size;
//using System.Windows.Forms;
//using HandyControl.Expression.Shapes;
//using System.Windows.Interop;

namespace SuporeSliplampApp.Views
{
    /// <summary>
    /// CameraView.xaml 的交互逻辑
    /// </summary>
    public delegate void SerialPortEventHandler(Object sender, SerialPortEventArgs e);
    public partial class CameraView : System.Windows.Controls.UserControl
    {
        public static uvcham cam_ = null;
        private WriteableBitmap bmp_ = null;
        public static IntPtr buf_ = IntPtr.Zero;
        private DispatcherTimer timer_ = null;
        private static bool started_ = false;
        private static bool successed = false;
        private uint count_ = 0;
        private delegate void msg(string s);
        BackgroundWorker worker;
        //窗体最大化
        private System.Windows.Window _fullScreenWindow = null;
        private DependencyObject _originalParent = null;
        private Grid grid = null;
        bool _maxed = false;
        int index = -1;
        private CameraSettingWindow settingWindow = null;
        public static event EventHandler<string> openImageDelegate;
        //EditPicControl t;
        PicEditView t;
        private DispatcherTimer timer;
        private DispatcherTimer timer2;
        SerialPort serialPort = null;
        bool isOpen = false;
        string End = Environment.NewLine;
        public string receivedValue = string.Empty;
        public event SerialPortEventHandler comReceiveDataEvent = null;  // 定义串口接收数据响应事件

        object thisLock = new object();
        string[] ports;
        bool isMessageReceived = false;
        int conectIndex = 0;
        int switchFlg = 3;
        public static PicEditView picEditView = null;
        AddPatientService service;
        ResultModel result = new ResultModel();

        //录像
        private OpenCvSharp.VideoWriter _videoWriter = null;
        private string _videoPath;
        private bool _isRecording = false;
        private object _videoWriteingLock = new object();
        private Task recordingTask;
        private readonly object _matLock = new object();

        //工程界面
        private bool showIF = false;

        //录像计时
        private DispatcherTimer _recordtimer;
        private TimeSpan _recordingTime;
        
        public CameraView()
        {
            InitializeComponent();

            service = new AddPatientService();
            _originalParent = this.Parent;
            this.Unloaded += (s, e) => { stopCamera(); };
            var fa = VisualTreeHelper.GetParent(this.testgrid);
            grid = (Grid)fa;
            loadCamera();
            ports = SerialPort.GetPortNames();
            this.DataContext = new CameraViewModel();
            ScrollControl.scrollDelegate += ScrollControl_scrollDelegate;
            ScrollControl.videoDelegate += ScrollControl_videoDelegate;
            //EditPicControl.analyseDalegate += EditPicControl_analyseDalegate;
            PicEditView.analyseDalegate += EditPicControl_analyseDalegate;
            ImgProcessView.imgprocessDelegate += PicEditView_imgprocessDelegate;

            VideoPlayerWindow.cutDelegate += VideoPlayerWindow_cutDelegate;
            AdminView.adminDelegate += AdminView_adminDelegate;

            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(500);
            timer.Tick += Timer_Tick;

            timer2 = new DispatcherTimer();
            timer2.Tick += Timer2_Tick;
            timer2.Start();

            if (Common.languageCode == "zh-CN")
            {
                examDate.Text = DateTime.Now.ToLongDateString();
            }
            else
            {
                examDate.Text = DateTime.Now.ToString("D", new CultureInfo("en-US"));
            }
            //examDate.Text = DateTime.Now.ToLongDateString();

            this.Loaded += CameraView_Loaded;
            this.Unloaded += CameraView_Unloaded;
            InitData();

            _recordtimer = new DispatcherTimer();
            _recordtimer.Interval = TimeSpan.FromSeconds(1);
            _recordtimer.Tick += RecordTimer_Tick;
            _recordingTime = TimeSpan.Zero;

            adminControl.Foreground = System.Windows.Media.Brushes.Transparent;

            Common.isAddToNow = false;
            Common.scrolllist = null;

            if (util.isPatientSelected)
            {
                BtnEdit.Visibility = Visibility.Hidden;
                BtnSave.Visibility = Visibility.Hidden;
            }
            else if (util.isPatientSelected == false)
            {
                BtnEdit.Visibility = Visibility.Visible;
                BtnSave.Visibility = Visibility.Visible;
            }

        }

        private void InitData()
        {

            nameTxt.Text = MainViewModel.GetInstance().patientModel.Name;
            pIdTxt.Text = MainViewModel.GetInstance().patientModel.P_ID;
            sexTxt.Text = MainViewModel.GetInstance().patientModel.SEX;
            datePicker.Text = MainViewModel.GetInstance().patientModel.Birth.ToLongDateString();
            adrTxt.Text = MainViewModel.GetInstance().patientModel.Adreess;
            teleTxt.Text = MainViewModel.GetInstance().patientModel.PhoneNum;
            mailTxt.Text = MainViewModel.GetInstance().patientModel.Email;
            //stackList.Children.Clear();
            if (!string.IsNullOrEmpty(pIdTxt.Text))
            {
                List<string> picHistory = new List<string>();
                picHistory = service.getPics(pIdTxt.Text);

                string extension;

                for (int i = 0; i < picHistory.Count; i++)
                {
                    extension = System.IO.Path.GetExtension(picHistory[i]);
                    if (extension == ".bmp" || extension == ".jpg" || extension == ".jpeg" )
                    {
                        ListControlModel model = new ListControlModel { ImgPath = picHistory[i], Name = System.IO.Path.GetFileNameWithoutExtension(picHistory[i]) };
                        ScrollControl scrollControl = new ScrollControl();
                        scrollControl.MyPicPath = model.ImgPath;
                        scrollControl.DataContext = model;

                        stackList.Children.Add(scrollControl);
                    }
                    else if (extension == ".avi" || extension == ".mp4")
                    {
                        VideoModel model = new VideoModel { VideoPath = picHistory[i], Name = System.IO.Path.GetFileNameWithoutExtension(picHistory[i]) };
                        ScrollControl scrollControl = new ScrollControl();
                        scrollControl.DataContext= model;
                        
                        stackList.Children.Add(scrollControl);
                    }


                    //ListControlModel model = new ListControlModel { ImgPath = picHistory[i], Name = System.IO.Path.GetFileNameWithoutExtension(picHistory[i]) };
                    //ScrollControl scrollControl = new ScrollControl();
                    //scrollControl.MyPicPath = model.ImgPath;
                    //TextBlock textBlock = new TextBlock();
                    //textBlock.MinHeight = 1.5;
                    //scrollControl.DataContext = model;
                    //stackList.Children.Add(scrollControl);
                    //stackList.Children.Add(textBlock);
                }
            }

        }



        private void CameraView_Unloaded(object sender, RoutedEventArgs e)
        {
            timer2.Stop();
            closePort();
            if (cam_ != null)
            {
                cam_.close();
            }
            if (picEditView != null)
            {
                picEditView.Close();
                //picEditView.timerStartEven -= PicEditView_timerStartEven;
                picEditView = null;
            }

        }

        /*private void ListenPort()
        {
            if (serialPort.IsOpen)
            {
                try
                {
                    while (true)
                    {
                        string data = serialPort.ReadExisting();
                        
                        if (!string.IsNullOrEmpty(data))
                        {
                            byte[] encodedBytes = Encoding.UTF8.GetBytes(data);
                            
                            for (int i = 0; i < encodedBytes.Length; i++)
                            {
                                receivedValue = receivedValue + encodedBytes[i];

                                // receivedValue += encodedBytes[i];

                            }
                            MessageBox.Show(receivedValue);
                            switch (receivedValue)
                            {
                                case "6320000263":
                                    rd1.IsChecked = true;
                                    rd2.IsChecked = false;
                                    lbl.Text = "OS";
                                    break;
                                case "6320010263":
                                    rd1.IsChecked = false;
                                    rd2.IsChecked = true;
                                    lbl.Text = "OD";
                                    break;
                                case "6330000363":
                                    break;
                                case "6330010363":
                                    TakePic();
                                    break;
                                default:
                                    rd1.IsChecked = true;
                                    rd2.IsChecked = false;
                                    lbl.Text = "OS";
                                    break;

                            }

                            receivedValue = string.Empty;
                        }
                       

                    }
                }
                catch 
                {
                }
                
            }
        }*/

        private void CameraView_Loaded(object sender, RoutedEventArgs e)
        {
            comReceiveDataEvent += new SerialPortEventHandler(ComReceiveDataEvent);
            if (ConectPort())
            {

                Task.Run(() =>
                {
                    timer.Start();
                });
                //timer.Start();

            }
            openCamera();

        }

        private void ComReceiveDataEvent(object sender, SerialPortEventArgs e)
        {
            try
            {
                Dispatcher.Invoke(new Action<Object, SerialPortEventArgs>(ComReceiveDataEvent), sender, e);
                System.Windows.MessageBox.Show(System.Text.Encoding.Default.GetString(e.receivedBytes));
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return;
        }

        private async void Timer_Tick(object sender, EventArgs e)
        {
            try
            {
                //Thread.Sleep(300);
                LeftRightQuery();
                await Task.Delay(200);
                TakePicQuery();
                await Task.Delay(200);
                if (isMessageReceived == false)
                {
                    Reconnect();
                }
            }
            catch (Exception ex)
            {

                //throw ex;
            }

            //if (cam_ == null)
            //{
            //    try
            //    {
            //        openCamera();

            //    }

            //    catch (Exception ex)
            //    {
            //        throw ex;
            //    }
            //}
            //if(cam_ ==null) openCamera();
            /* Task.Run(() =>
             {
                 try
                 {
                     Thread.Sleep(200);
                     LeftRightQuery();
                     Thread.Sleep(200);
                     TakePicQuery();
                     Thread.Sleep(200);
                     if (SerialPortHelper.isPhoto == true)
                     {
                         TakePic();
                         SerialPortHelper.isPhoto = false;
                     }
                     if (SerialPortHelper.eyeFlg == "0")
                     {
                         ck1.IsChecked = true;
                         ck2.IsChecked = false;
                         lbl.Text = "OS";
                     }
                     else if (SerialPortHelper.eyeFlg == "1")
                     {
                         ck1.IsChecked = false;
                         ck2.IsChecked = true;
                         lbl.Text = "OD";
                     }
                 }
                 catch (Exception ex)
                 {

                     throw ex;
                 }
             });*/

        }

        private void Timer2_Tick(object sender, EventArgs e)
        {
            if(cam_ == null)
            {
                openCamera();
                lbl.Text = "等待重新连接……";
            }
        }



        private void Reconnect()
        {
            closePort();

            string bauRate = "94600";
            for (int i = conectIndex; i < ports.Length; i++)
            {
                serialPort = new SerialPort(ports[conectIndex], 38400, Parity.None, 8, StopBits.One);
                serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
                try
                {
                    serialPort.Open();
                    isOpen = true;
                    conectIndex++;

                    //if(isMessageReceived == true)System.Windows.MessageBox.Show($"串口连接成功: {ports[conectIndex]}", "连接成功", MessageBoxButton.OK, MessageBoxImage.Information);
                    break;

                }
                catch (Exception ex)
                {
                }
            }

        }

        private void LeftRightQuery()
        {
            byte[] buffer = new byte[] { 0xFE, 0x2, 0x0, 0x0, 0x0, 0x0, 0x2, 0xFF };
            SengInstructions(buffer);
        }

        private void TakePicQuery()
        {
            byte[] buffer = new byte[] { 0xFE, 0x3, 0x0, 0x0, 0x0, 0x0, 0x3, 0xFF };
            SengInstructions(buffer);
        }

        private void EditPicControl_analyseDalegate(object sender, ListControlModel e)
        {
            ListControlModel model = new ListControlModel { ImgPath = e.ImgPath, Name = e.Name };
            ScrollControl scrollControl = new ScrollControl();
            TextBlock textBlock = new TextBlock();
            textBlock.MinHeight = 1.5;
            scrollControl.DataContext = model;
            stackList.Children.Add(scrollControl);
            stackList.Children.Add(textBlock);
        }

        private void closePort()
        {

            try
            {
                if (serialPort != null)
                {
                    if (serialPort.IsOpen)
                        serialPort.Close();
                    serialPort.Dispose();
                }
            }
            catch (Exception)
            {

                //throw;
            }
        }

        private void SengInstructions(byte[] data)
        {
            if (isOpen)
            {
                SerialPortWrite(data);
            }
            else
            {
                //if (Common.languageCode == "zh-CN")
                //{
                //    MessageView messageView = new MessageView("请先连接串口!", 0);
                //    messageView.Owner = System.Windows.Application.Current.Windows.OfType<Window>().FirstOrDefault(w => w.IsActive);
                //    messageView.ShowDialog();
                //}
                //else
                //{
                //    MessageView messageView = new MessageView("Please connect the serial port first!", 0);
                //    messageView.Owner = System.Windows.Application.Current.Windows.OfType<Window>().FirstOrDefault(w => w.IsActive);
                //    messageView.ShowDialog();
                //}
                return;
            }

        }

        private bool ConectPort()
        {
            closePort();

            string bauRate = "94600";
            bool res = false;
            foreach (string port in ports)
            {
                //LeftRightQuery();
                serialPort = new SerialPort(port, 38400, Parity.None, 8, StopBits.One);
                serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
                try
                {
                    serialPort.Open();
                    res = true;
                    isOpen = true;
                    conectIndex++;

                    //if(isMessageReceived == true) System.Windows.MessageBox.Show($"串口连接成功: {port}", "连接成功", MessageBoxButton.OK, MessageBoxImage.Information);

                    break;
                }
                catch (Exception ex)
                {
                    res = false;
                }
            }
            return res;

        }

        private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {
            lock (thisLock)
            {

                //isMessageReceived = false;

                SerialPort sp = (SerialPort)sender;
                string data = sp.ReadExisting();
                string s = string.Empty;
                byte[] encodedBytes = Encoding.UTF8.GetBytes(data);
                for (int i = 0; i < encodedBytes.Length; i++)
                {
                    receivedValue = receivedValue + encodedBytes[i];

                    // receivedValue += encodedBytes[i];

                }

                Console.WriteLine("接收：" + receivedValue);
                //MessageBox.Show(receivedValue);
                switch (receivedValue)
                {
                    case "6320000263":
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            rd1.IsChecked = true;
                            rd2.IsChecked = false;
                            lbl.Text = "OS";
                            isMessageReceived = true;
                        }));

                        break;
                    case "6320010363":
                        Dispatcher.BeginInvoke((Action)(() =>
                        {
                            rd1.IsChecked = false;
                            rd2.IsChecked = true;
                            lbl.Text = "OD";
                            isMessageReceived = true;
                        }));

                        break;
                    case "6330000363":
                        isMessageReceived = true;
                        break;
                    case "6330010463":
                        Dispatcher.BeginInvoke((Action)(() =>
                        {
                            TakePic();
                        }));
                        isMessageReceived = true;
                        break;
                    case "63200002636320010363":
                        isMessageReceived = true;
                        break;
                    //case "0":
                    //    isMessageReceived = false;
                    //    break;
                    default:
                        //Dispatcher.BeginInvoke((Action)(() =>
                        //{
                        //    rd1.IsChecked = true;
                        //    rd2.IsChecked = false;
                        //    lbl.Text = "OS";
                        //}));
                        //isMessageReceived = false;

                        break;
                }

            }
            Thread.Sleep(200);
            receivedValue = string.Empty;
        }

        public bool ReceiveData()
        {
            if (serialPort == null)
            {
                return false;
            }
            if (serialPort.IsOpen == false)
            {
                return false;
            }
            if (serialPort.BytesToRead <= 0)
            {
                return false;
            }
            lock (thisLock)
            {
                int len = serialPort.BytesToRead;
                byte[] data = new byte[len];

                try
                {
                    serialPort.Read(data, 0, len);
                }
                catch (Exception)
                {
                    if (Common.languageCode == "zh-CN")
                    {
                        MessageView messageView = new MessageView("数据接收失败!", 0);
                        messageView.Owner = System.Windows.Application.Current.Windows.OfType<Window>().FirstOrDefault(w => w.IsActive);
                        messageView.ShowDialog();
                    }
                    else
                    {
                        MessageView messageView = new MessageView("Data Reception Failed!", 0);
                        messageView.Owner = System.Windows.Application.Current.Windows.OfType<Window>().FirstOrDefault(w => w.IsActive);
                        messageView.ShowDialog();
                    }
                    return false;
                }
                SerialPortEventArgs args = new SerialPortEventArgs();
                args.receivedBytes = data;
                if (comReceiveDataEvent != null)
                {
                    comReceiveDataEvent.Invoke(this, args);
                }
            }

            return true;
        }

        private bool SerialPortWrite(byte[] data)
        {
            try
            {
                string res = string.Join(" ", data);
                Console.WriteLine("发送：" + res);
                serialPort.Write(data, 0, data.Length);
                return true;

            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error sending data: {ex.Message}");
                return false;
            }
        }

        private void ScrollControl_scrollDelegate(object sender, ListControlModel e)
        {
            removeChild();
            ListControlModel model = new ListControlModel();
            hideOrShowOtherButton();
            model = e;
            //if (t != null)
            //{
            //    testgrid.Children.Remove(t);
            //}
            //t = new EditPicControl(model);                    
            //testgrid.Children.Add(t);
            if (timer.IsEnabled == true)
            {
                timer.Stop();
            }
            if (util.ComboBox_SelectedIndex == 0)
            {
                if (picEditView == null)
                {
                    //System.Windows.MessageBox.Show("null");
                    //picEditView.Close();
                    //picEditView = null;
                    picEditView = new PicEditView(model);
                    picEditView.Owner = GetParentWindow(this);      
                    //picEditView.timerStartEven += PicEditView_timerStartEven;

                    picEditView.Left = Common.picpostion.X + 8;
                    picEditView.Top = Common.picpostion.Y + 218;

                    picEditView.Show();

                    //picEditView.ImgShow.Stretch = Stretch.Fill;
                    //picEditView.Activate();
                    //System.Windows.Point p = lbl.PointToScreen(new System.Windows.Point(0, 0));

                }
                else
                {
                    //System.Windows.MessageBox.Show("not null");

                    //picEditView.Close();
                    //picEditView = new PicEditView(model);
                    //picEditView.timerStartEven += PicEditView_timerStartEven;
                    //picEditView.Show();
                    //System.Windows.Point p = lbl.PointToScreen(new System.Windows.Point(0, 0));
                    //picEditView = null;
                    picEditView.Close();
                    picEditView = new PicEditView(model);
                    picEditView.Owner = GetParentWindow(this);

                    picEditView.Left = Common.picpostion.X + 8;
                    picEditView.Top = Common.picpostion.Y + 218;

                    picEditView.Show();
                    //picEditView.Activate();
                    //picEditView.timerStartEven += PicEditView_timerStartEven;
                    //System.Windows.Point p = lbl.PointToScreen(new System.Windows.Point(0, 0));


                    //SetImageSource(model);
                    //picEditView.Activate();
                    picEditView.Topmost = true;
                }
            }
            else
            {
                SetImageSource(model);
                picEditView.Activate();
                picEditView.Topmost = true;
                //picEditView.Show();
            }

            if (timer.IsEnabled == true)
            {
                timer.Stop();
            }


        }

        private void SetImageSource(ListControlModel model)
        {


            try
            {
                switch (util.Image_SelectedIndex)
                {
                    case 1:
                        picEditView.ImgShow.Source = new BitmapImage(new Uri(model.ImgPath));
                        break;
                    case 2:
                        picEditView.ImgShow2.Source = new BitmapImage(new Uri(model.ImgPath));
                        break;
                    case 3:
                        picEditView.ImgShow3.Source = new BitmapImage(new Uri(model.ImgPath));
                        break;
                    case 4:
                        picEditView.ImgShow4.Source = new BitmapImage(new Uri(model.ImgPath));
                        break;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

        }




        private void PicEditView_timerStartEven(object sender, EventArgs e)
        {
            if (picEditView == null) return;
            if (timer.IsEnabled == false)
            {
                DependencyObject obj = VisualTreeHelper.GetParent(this);
                List<System.Windows.Controls.Button> btnList = WindowOperator.FindVisualChild<System.Windows.Controls.Button>(obj);
                foreach (var item in btnList)
                {
                    if (item != null)
                        item.Visibility = Visibility.Visible;
                }
                //reopen.Visibility = Visibility.Collapsed;
                timer.Start();
            }
        }

        private void RemoveChildElement(Grid grid, UIElement elementToRemove)
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(grid); i++)
            {
                UIElement child = VisualTreeHelper.GetChild(grid, i) as UIElement;
                if (child == elementToRemove)
                {
                    grid.Children.Remove(child);
                    break;
                }
            }
        }

        private void removeChild()
        {
            DependencyObject obj = VisualTreeHelper.GetParent(this);
            EditPicControl editPicControl = obj as EditPicControl;
            if (obj is System.Windows.Controls.Panel panel)
            {
                if (panel.Children.Contains(editPicControl))
                    panel.Children.Remove(editPicControl);
            }
        }

        private void loadCamera()
        {
            if (worker != null) return;
            worker = new BackgroundWorker();
            worker.WorkerReportsProgress = true;
            worker.DoWork += Worker_DoWork;
            worker.ProgressChanged += Worker_ProgressChanged;
            worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
            worker.RunWorkerAsync();
            //if(successed)
            //    timer.Start();
        }

        private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (successed)
            {
                lbl.Text = "";

            }
            //lbl.Visibility = Visibility.Collapsed;

        }

        private void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            throw new NotImplementedException();
        }

        private void Worker_DoWork(object sender, DoWorkEventArgs e)
        {
            //openCamera();
        }

        private void BtnEdit_Click(object sender, RoutedEventArgs e)
        {
            Common.scrolllist = WindowOperator.GetChildObjects<ScrollControl>(stackList, typeof(ScrollControl)); 
            Common.isAddToNow = true;
            OpenPatients openPatients = new OpenPatients();
            openPatients.Owner = GetParentWindow(this);
            openPatients.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            openPatients.ShowDialog();
        }

        private void BtnSave_Click(object sender, RoutedEventArgs e)
        {
            PrintModel printModel = new PrintModel();
            printModel.Patient = new PatientModel();
            printModel.ExamDate = examDate.Text.Trim();
            printModel.ExamResult = examResult.Text.Trim();
            printModel.ExamType = examType.Text.Trim();
            printModel.Patient.Name = nameTxt.Text.Trim();
            printModel.Patient.P_ID = pIdTxt.Text.Trim();

            ComboBoxItem selectedCBI = sexTxt.SelectedItem as ComboBoxItem;
            if (selectedCBI != null)
            {
                printModel.Patient.SEX = selectedCBI.Content.ToString().Trim();
            }

            //printModel.Patient.Str_Birth = datePicker.Text.Trim();

            if (datePicker.SelectedDate.HasValue)
            {
                printModel.Patient.Str_Birth = datePicker.SelectedDate.Value.ToString("yyyy-MM-dd").Trim();
            }
            else
            {
                // 处理没有选择日期的情况，或设置一个默认值
                printModel.Patient.Str_Birth = "";
            }

            printModel.Patient.Adreess = adrTxt.Text.Trim();
            printModel.Patient.PhoneNum = teleTxt.Text.Trim();
            printModel.Patient.Email = mailTxt.Text.Trim();
            printModel.Patient.Creator = doctor.Text.Trim();
            printModel.ExamType = examType.Text.Trim();
            printModel.ExamResult = examResult.Text.Trim();
            PrintView printView = new PrintView(printModel);
            printView.Owner = GetParentWindow(this);
            printView.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            printView.ShowDialog();
        }

        private void PhotoButton_Click(object sender, RoutedEventArgs e)
        {

            //System.Windows.MessageBox.Show("test");

            PlayShutterSound();
            TakePic();



        }

        private void PlayShutterSound()
        {
            try
            {
                string soundPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "1.wav");
                Uri soundUri = new Uri(soundPath, UriKind.Absolute);
                MediaPlayer player = new MediaPlayer();
                player.Volume = 1.0;
                player.Open(soundUri);
                player.MediaOpened += (sender, args) =>
                {
                    player.Play();
                };
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show("拍照音效失败: " + ex.Message);
            }
        }


        //private void RecordButton_Click(object sender, RoutedEventArgs e)
        //{
        //    if (cam_ == null)
        //    {
        //        System.Windows.MessageBox.Show("未开启摄像头");
        //        return;
        //    }

        //    if (_isRecording)
        //    {
        //        try
        //        {
        //            //停止录像操作
        //            cam_.record(null);

        //            //使用 Dispatcher.Invoke 更新UI
        //            Dispatcher.Invoke(() =>
        //            {
        //                _isRecording = false;
        //                recordButton.Content = "\uE636";
        //            });
        //        }
        //        catch (Exception ex)
        //        {
        //            Dispatcher.Invoke(() =>
        //            {
        //                System.Windows.MessageBox.Show($"停止录像时发生错误: {ex.Message}");
        //            });
        //        }
        //    }
        //    else if (!_isRecording)
        //    {
        //        try
        //        {
        //            string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
        //            string folderPath = System.IO.Path.Combine(desktopPath, "1");
        //            string fileName = $"ScreenVideo-{DateTime.Now:yyyyMMdd_HHmmss}.mp4";
        //            string fullPath = System.IO.Path.Combine(folderPath, fileName);

        //            //确保文件夹存在
        //            Directory.CreateDirectory(folderPath);

        //            //在后台线程中启动录像
        //            Task.Run(() =>
        //            {
        //                cam_.record(fullPath); // 启动录像

        //                //使用 Dispatcher.Invoke 更新UId
        //                Dispatcher.Invoke(() =>
        //                {
        //                    recordButton.Content = "\ue64d";
        //                    _isRecording = true;
        //                });
        //            });
        //        }
        //        catch (Exception ex)
        //        {
        //            Dispatcher.Invoke(() =>
        //            {
        //                System.Windows.MessageBox.Show($"启动录像时发生错误: {ex.Message}");
        //            });
        //        }
        //    }
        //}


        //private void RecordButton_Click(object sender, RoutedEventArgs e)
        //{
        //    if (cam_ == null)
        //    {
        //        System.Windows.MessageBox.Show("未开启摄像头");
        //        return;
        //    }

        //    if (_isRecording)
        //    {
        //        _isRecording = false;
        //        lock (_videoWriteingLock)
        //        {
        //            _videoWriter?.Release();
        //            _videoWriter?.Dispose();
        //            _videoWriter = null;
        //        }

        //        AddVideoToList();
        //        System.Windows.MessageBox.Show("视频录制完成");
        //    }
        //    else if (!_isRecording)
        //    {
        //        _isRecording = true;

        //        string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
        //        string folderPath = System.IO.Path.Combine(desktopPath, "1");

        //        if (!Directory.Exists(folderPath))
        //        {
        //            Directory.CreateDirectory(folderPath);
        //        }

        //        string fileName = $"ScreenVideo-{DateTime.Now:yyyyMMdd_HHmmss}.avi";
        //        string fullPath = System.IO.Path.Combine(folderPath, fileName);

        //        try
        //        {
        //            _videoWriter = new OpenCvSharp.VideoWriter(fullPath, OpenCvSharp.FourCC.XVID, 30, new OpenCvSharp.Size(bmp_.PixelWidth, bmp_.PixelHeight), true);
        //            System.Windows.MessageBox.Show("开始录像");
        //        }
        //        catch (Exception ex)
        //        {
        //            System.Windows.MessageBox.Show($"无法启动录像: {ex.Message}");
        //            _isRecording = false;
        //            return;
        //        }
        //    }
        //}



        //private void RecordButton_Click(object sender, RoutedEventArgs e)
        //{
        //    if (!_isRecording)
        //    {
        //        //开始录制
        //        int Width, Height;
        //        cam_.get(uvcham.eCMD.WIDTH, out Width);
        //        cam_.get(uvcham.eCMD.HEIGHT, out Height);

        //        _videoPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, DateTime.Now.ToString("yyyyMMddHHmmss") + ".avi");
        //        int fourcc = VideoWriter.Fourcc('M', 'J', 'P', 'G');  // 定义编码器
        //        var frameSize = new System.Drawing.Size(Width, Height);
        //        _videoWriter = new VideoWriter(_videoPath, fourcc, 20, frameSize, true);

        //        if (!_videoWriter.IsOpened)
        //        {
        //            MessageBox.Show("无法创建视频文件");
        //            return;
        //        }


        //        Task.Run(() =>
        //        {
        //            cam_.Start(); 


        //            _isRecording = true;
        //            this.Dispatcher.Invoke(() => recordButton.Content = "嘿");

        //            while (_isRecording)
        //            {
        //                Mat frame = new Mat();

        //                Thread.Sleep(500);
        //                cam_.Retrieve(frame);  // 从相机获取一帧

        //                Mat rgbFrame = new Mat();
        //                CvInvoke.CvtColor(frame, rgbFrame, Emgu.CV.CvEnum.ColorConversion.Bgra2Rgb); // 转换为RGBB

        //                if (!frame.IsEmpty)
        //                {
        //                    _videoWriter.Write(frame);
        //                    Console.WriteLine("帧已写入");
        //                }
        //                else
        //                {
        //                    Console.WriteLine("获取帧失败");
        //                }
        //            }

        //            cam_.Stop();
        //            _videoWriter.Dispose();  // 关闭并释放视频文件写入器
        //            this.Dispatcher.Invoke(() => recordButton.Content = "☺");

        //            if (File.Exists(_videoPath))
        //            {
        //                var fileInfo = new FileInfo(_videoPath);
        //                if (fileInfo.Length > 0)
        //                {
        //                    this.Dispatcher.Invoke(() => MessageBox.Show("视频录制成功，文件大小: " + fileInfo.Length + " 字节"));
        //                    ShowVideoPlayerWindow(_videoPath);
        //                    AddVideoToList();
        //                }
        //                else
        //                {
        //                    this.Dispatcher.Invoke(() => MessageBox.Show("视频录制失败，文件大小为0"));
        //                }
        //            }
        //            else
        //            {
        //                this.Dispatcher.Invoke(() => MessageBox.Show("视频录制失败，文件未创建"));
        //            }

        //            this.Dispatcher.Invoke(() => AddVideoToList());
        //        });
        //    }
        //    else
        //    {
        //        _isRecording = false;  // 停止录制循环
        //    }
        //}


        private string fullPath;

        private void RecordButton_Click(object sender, RoutedEventArgs e)
        {
            if (cam_ == null)
            {
                if (Common.languageCode == "zh-CN")
                {
                    MessageView messageView = new MessageView("未开启摄像头", 0);
                    messageView.Owner = System.Windows.Application.Current.Windows.OfType<Window>().FirstOrDefault(w => w.IsActive);
                    messageView.ShowDialog();
                }
                else
                {
                    MessageView messageView = new MessageView("Camera Disconnected", 0);
                    messageView.Owner = System.Windows.Application.Current.Windows.OfType<Window>().FirstOrDefault(w => w.IsActive);
                    messageView.ShowDialog();
                }
            }


            if (cam_ != null)
            {
                if (_isRecording)
                {
                    cam_.record(null);
                    _isRecording = false;
                    recordButton.Content = "\ue636";
                    AddVideoToList();

                    _recordtimer.Stop();
                }
                else if (!_isRecording)
                {
                    //string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
                    //string folderPath = System.IO.Path.Combine(desktopPath, "1");
                    //string fileName = $"ScreenVideo-{DateTime.Now:yyyyMMdd_HHmmss}.avi";
                    //fullPath = System.IO.Path.Combine(folderPath, fileName);

                    //// 确保文件夹存在
                    //if (!Directory.Exists(folderPath))
                    //{
                    //    Directory.CreateDirectory(folderPath);
                    //}
                    //if (!Directory.Exists(System.IO.Path.GetDirectoryName(fullPath)))
                    //{
                    //    Directory.CreateDirectory(System.IO.Path.GetDirectoryName(fullPath));
                    //}

                    string appRootPath = AppDomain.CurrentDomain.BaseDirectory; // 程序根路径
                    string fileName = $"ScreenVideo-{DateTime.Now:yyyyMMdd_HHmmss}.avi";
                    fullPath = System.IO.Path.Combine(appRootPath, fileName);

                    cam_.record(fullPath);
                    recordButton.Content = "\ue64d";
                    _isRecording = true;

                    _recordingTime = TimeSpan.Zero;
                    recordTime.Text = "00:00:00";
                    _recordtimer.Start();

                }
            }
        }



        private void AddVideoToList()
        {
            VideoModel video = new VideoModel { Name = System.IO.Path.GetFileName(fullPath), VideoPath = fullPath };
            ScrollControl videoControl = new ScrollControl();  // 自定义的 ScrollControl 来显示视频信息
            videoControl.DataContext = video;
            stackList.Children.Add(videoControl);


            if (util.isPatientSelected == true)
            {
                result.Id = pIdTxt.Text;
                result.Description = examResult.Text;
                result.Date = DateTime.Now;
                result.Path = video.VideoPath;
                result.Name = video.Name;
                service.SaveResults(result);
            }


        }


        public void ShowVideoPlayerWindow(string videoPath)
        {
            VideoPlayerWindow videoPlayerWindow = new VideoPlayerWindow(videoPath);
            videoPlayerWindow.Owner = GetParentWindow(this);
            videoPlayerWindow.Left = Common.picpostion.X + 8;
            videoPlayerWindow.Top = Common.picpostion.Y + 218;
            videoPlayerWindow.ShowDialog();
        }


        private void TakePic()
        {
            bool previousShowIF = IFCheck.IsChecked ?? false;
            IFCheck.IsChecked = false;

            //player = new MediaPlayer();
            //player.Open(new Uri(soundPath, UriKind.RelativeOrAbsolute));
            //player.Volume = 1.0;
            //player.Play();
            //player.MediaEnded += OnMediaEnded;
            //System.Media.SystemSounds.Exclamation.Play();
            //sound.Play();

            string _pathStr = DateTime.Now.ToString("yyyyMMddHHmmfff") + ".bmp";
            ListControlModel dt = new ListControlModel();
            try
            {
                if ((cam_ != null) && (bmp_ != null))
                {
                    //using (FileStream fileStream = new FileStream((@"\Image\" +DateTime.Now.ToString("yyyyMMddHHmmss")), FileMode.Create))
                    using (FileStream fileStream = new FileStream(_pathStr, FileMode.Create))
                    {
                        BitmapEncoder encoder = new BmpBitmapEncoder();
                        encoder.Frames.Add(BitmapFrame.Create(bmp_));
                        encoder.Save(fileStream);
                        //camModel.VM_Model.Add(new Model() { Path = System.AppDomain.CurrentDomain.BaseDirectory+ _pathStr });
                        //CameraViewModel.camModel.VM_Model.Add(new Model() { Path = System.AppDomain.CurrentDomain.BaseDirectory + _pathStr,Name=_pathStr.Substring(0,_pathStr.LastIndexOf(".")) });
                    }

                    ListControlModel model = new ListControlModel { ImgPath = System.AppDomain.CurrentDomain.BaseDirectory + _pathStr, Name = _pathStr };
                    ScrollControl scrollControl = new ScrollControl();
                    TextBlock textBlock = new TextBlock();
                    textBlock.MinHeight = 1.5;
                    scrollControl.DataContext = model;
                    stackList.Children.Add(scrollControl);
                    //stackList.Children.Add(textBlock);

                    IFCheck.IsChecked = previousShowIF;

                    /****************************************************************/

                    if (dt != null)
                    {
                        dt.ImgPath = System.AppDomain.CurrentDomain.BaseDirectory + _pathStr;
                        dt.ImageName = _pathStr;
                        //if (t != null)
                        //{
                        //    testgrid.Children.Remove(t);
                        //}
                        //t = new PicEditView(dt);
                        ////picEditView = t;
                        //t.timerStartEven += PicEditView_timerStartEven;
                        ////testgrid.Children.Add(t);
                        ////t.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                        //if (timer.IsEnabled == true)
                        //{
                        //    timer.Stop();
                        //}
                        //t.Show();
                        //System.Windows.Point p = lbl.PointToScreen(new System.Windows.Point(0, 0));
                        //t.Left = p.X - 2;
                        //t.Top = p.Y - 2;

                        if (util.isPatientSelected == true)
                        {
                            result.Id = pIdTxt.Text;
                            result.Description = examResult.Text;
                            result.Date = DateTime.Now;
                            result.Path = dt.ImgPath;
                            result.Name = dt.ImageName;
                            service.SaveResults(result);
                        }
                    }
                }
            }
            catch (IOException ex)
            {
                System.Windows.MessageBox.Show(ex.ToString());
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.ToString());
            }
        }



        private void openCamera()
        {
            if (cam_ != null)
                return;
            uvcham.Device[] arr = uvcham.Enum();
            if (arr.Length <= 0)
            {
                // MessageBox.Show("未找到相机");
                //lbl.invoke();
                System.Windows.Application.Current.Dispatcher.Invoke(() => lbl.Text = "未找到相机");
                //reopen.Visibility = Visibility.Visible;
            }

            else if (1 == arr.Length)
            {
                successed = true;
                startDevice(arr[0].id);
                //started_=true;
            }

        }

        //private void startDevice(string id)
        //{
        //    cam_ = uvcham.open(id);
        //    if (cam_ != null)
        //    {
        //        cam_.put(uvcham.eCMD.FORMAT, 1);
        //        cam_.put(uvcham.eCMD.WBMODE, 1);
        //        cam_.put(uvcham.eCMD.USER, 1);
        //        CommonData.Expo_enabled = true;
        //        CommonData.balance_enabled = true;
        //        int width = 0, height = 0, res = 0;
        //        cam_.get(uvcham.eCMD.RES, out res);
        //        cam_.get(uvcham.eCMD.WIDTH | ((uvcham.eCMD)res), out width);
        //        cam_.get(uvcham.eCMD.HEIGHT | ((uvcham.eCMD)res), out height);
        //        //height += 40;
        //        if ((width > 0) && (height > 0))
        //        {
        //            buf_ = Marshal.AllocHGlobal(uvcham.TDIBWIDTHBYTES(width * 32) * height);
        //            //bmp_ = new WriteableBitmap(width, height, 0, 0, PixelFormats.Bgr32, null);
        //            if (cam_.start(buf_, (nEvent) =>
        //            {
        //                Dispatcher.BeginInvoke((Action)(() =>
        //                {
        //                    if (cam_ != null)
        //                    {
        //                        if ((nEvent & uvcham.eEVENT.IMAGE) != 0)
        //                        {
        //                            //lbl.Visibility = Visibility.Collapsed;
        //                            //Task.Run(()=> { OnEventImage(); });
        //                            OnEventImage(width, height);
        //                            //OnEventImage();

        //                            //lbl.Text = "UI线程";
        //                            // MessageBox.Show("打开了");
        //                        }

        //                        else if ((nEvent & uvcham.eEVENT.ERROR) != 0)
        //                            OnEventError();
        //                        else if ((nEvent & uvcham.eEVENT.DISCONNECT) != 0)
        //                            OnEventDisconnect();


        //                    }
        //                }));
        //            }) < 0)
        //            {
        //                System.Windows.MessageBox.Show("相机启动失败");
        //            }
        //            else
        //            {
        //                int nmin, nmax, ndef;
        //                cam_.range(uvcham.eCMD.EXPOTIME, out nmin, out nmax, out ndef);
        //                CommonData.ExpoSlider_Max = nmax;
        //                CommonData.ExpoSlider_Min = nmin;
        //                cam_.range(uvcham.eCMD.WBRED, out nmin, out nmax, out ndef);
        //                CommonData.R_Max = nmax;
        //                CommonData.R_Min = nmin;
        //                cam_.range(uvcham.eCMD.WBGREEN, out nmin, out nmax, out ndef);
        //                CommonData.G_Max = nmax;
        //                CommonData.G_Min = nmin;
        //                cam_.range(uvcham.eCMD.WBBLUE, out nmin, out nmax, out ndef);
        //                CommonData.B_Max = nmax;
        //                CommonData.B_Min = nmin;
        //                UpdateExpoTime();
        //                UpdateAwb();
        //                int val = 0;
        //                cam_.get(uvcham.eCMD.AEXPO, out val);
        //                CommonData.Expo_checked = (1 == val);
        //                CommonData.ExpoSlider_enabled = (1 != val);
        //                cam_.get(uvcham.eCMD.WBMODE, out val);
        //                CommonData.Expo_checked = (1 == val);
        //                CommonData.R_enabled = (1 != val);
        //                CommonData.G_enabled = (1 != val);
        //                CommonData.B_enabled = (1 != val);
        //                timer_ = new DispatcherTimer() { Interval = new TimeSpan(0, 0, 1) };
        //                timer_.Tick += (object sender, EventArgs e) =>
        //                {
        //                    if (cam_ != null)
        //                    {
        //                        if (CommonData.Expo_checked)
        //                            UpdateExpoTime();
        //                        if (CommonData.balance_checked)
        //                            UpdateAwb();
        //                    }
        //                };
        //                timer_.Start();
        //            }
        //            CommonData.started_ = true;
        //        }
        //    }
        //}

        private void startDevice(string id)
        {
            cam_ = uvcham.open(id);
            if (cam_ != null)
            {
                cam_.put(uvcham.eCMD.FORMAT, 1);
                cam_.put(uvcham.eCMD.WBMODE, 0);
                cam_.put(uvcham.eCMD.USER, 1);
                cam_.put(uvcham.eCMD.AEXPO, 0);
                cam_.put(uvcham.eCMD.SHARPNESS,1);
                cam_.put(uvcham.eCMD.DENOISE,1);

                CameraView.cam_?.put(uvcham.eCMD.WBRED, 50);
                CameraView.cam_?.put(uvcham.eCMD.WBGREEN, 68);
                CameraView.cam_?.put(uvcham.eCMD.WBBLUE, 328);

                CommonData.Expo_enabled = true;
                CommonData.balance_enabled = true;
                int width = 0, height = 0, res = 0;
                cam_.get(uvcham.eCMD.RES, out res);
                cam_.get(uvcham.eCMD.WIDTH | ((uvcham.eCMD)res), out width);
                cam_.get(uvcham.eCMD.HEIGHT | ((uvcham.eCMD)res), out height);
                //height += 40;
                if ((width > 0) && (height > 0))
                {
                    cam_.put(uvcham.eCMD.FORMAT, 1);
                    //buf_ = Marshal.AllocHGlobal(uvcham.TDIBWIDTHBYTES(width * 32) * height);
                    bmp_ = new WriteableBitmap(width, height, 0, 0, PixelFormats.Bgr32, null);
                    if (cam_.start(IntPtr.Zero/* Pull Mode */, (nEvent) =>
                    {
                        /* this is called by internal thread of uvcham.dll which is NOT the same of UI thread.
                         * So we use BeginInvoke
                         */
                        Dispatcher.BeginInvoke((Action)(() =>
                        {
                            /* this run in the UI thread */
                            if (cam_ != null)
                            {
                                if ((nEvent & uvcham.eEVENT.IMAGE) != 0)
                                    OnEventImage();
                                else if ((nEvent & uvcham.eEVENT.ERROR) != 0)
                                    OnEventError();
                                else if ((nEvent & uvcham.eEVENT.DISCONNECT) != 0)
                                {
                                    OnEventDisconnect();
                                    //reopen.Visibility = Visibility.Visible;
                                }


                            }
                        }));
                    }) < 0)
                    {
                        if (Common.languageCode == "zh-CN")
                        {
                            MessageView messageView = new MessageView("相机启动失败", 0);
                            messageView.Owner = System.Windows.Application.Current.Windows.OfType<Window>().FirstOrDefault(w => w.IsActive);
                            messageView.ShowDialog();
                        }
                        else
                        {
                            MessageView messageView = new MessageView("Camera Initialization Failed", 0);
                            messageView.Owner = System.Windows.Application.Current.Windows.OfType<Window>().FirstOrDefault(w => w.IsActive);
                            messageView.ShowDialog();
                        }
                    }
                    else
                    {
                        int nmin, nmax, ndef;
                        cam_.range(uvcham.eCMD.EXPOTIME, out nmin, out nmax, out ndef);
                        CommonData.ExpoSlider_Max = nmax;
                        CommonData.ExpoSlider_Min = nmin;
                        cam_.range(uvcham.eCMD.WBRED, out nmin, out nmax, out ndef);
                        CommonData.R_Max = nmax;
                        CommonData.R_Min = nmin;
                        cam_.range(uvcham.eCMD.WBGREEN, out nmin, out nmax, out ndef);
                        CommonData.G_Max = nmax;
                        CommonData.G_Min = nmin;
                        cam_.range(uvcham.eCMD.WBBLUE, out nmin, out nmax, out ndef);
                        CommonData.B_Max = nmax;
                        CommonData.B_Min = nmin;
                        UpdateExpoTime();
                        UpdateAwb();
                        int val = 0;
                        cam_.get(uvcham.eCMD.AEXPO, out val);
                        CommonData.Expo_checked = (1 == val);
                        CommonData.ExpoSlider_enabled = (1 != val);
                        cam_.get(uvcham.eCMD.WBMODE, out val);
                        CommonData.Expo_checked = (1 == val);
                        CommonData.R_enabled = (1 != val);
                        CommonData.G_enabled = (1 != val);
                        CommonData.B_enabled = (1 != val);
                        timer_ = new DispatcherTimer() { Interval = new TimeSpan(0, 0, 1) };
                        timer_.Tick += (object sender, EventArgs e) =>
                        {
                            if (cam_ != null)
                            {
                                if (CommonData.Expo_checked)
                                    UpdateExpoTime();
                                if (CommonData.balance_checked)
                                    UpdateAwb();
                            }
                        };
                        timer_.Start();
                    }
                    CommonData.started_ = true;
                }
            }
        }

        private Bitmap bitbmp_;
        private WriteableBitmap bmpClone;

        //private void OnEventImage(int _width, int _height)
        //{
        //    if (bmp_ == null)
        //        bmp_ = new WriteableBitmap(_width, _height, 0, 0, PixelFormats.Bgr32, null);

        //    if (bmp_ != null)
        //    {
        //        try
        //        {
        //            bmp_.Lock();
        //            try
        //            {
        //                uvcham.memcpy(bmp_.BackBuffer, buf_, new IntPtr(uvcham.TDIBWIDTHBYTES(bmp_.PixelWidth * 32) * bmp_.PixelHeight));
        //                bmp_.AddDirtyRect(new Int32Rect(0, 0, bmp_.PixelWidth, bmp_.PixelHeight));

        //            }
        //            finally
        //            {
        //                bmp_.Unlock();
        //            }

        //            if (showIF)
        //            {
        //                DrawIF(bmp_);
        //            }

        //            image_.Source = bmp_;


        //            if (_isRecording)
        //            {
        //                int width = bmp_.PixelWidth;
        //                int height = bmp_.PixelHeight;
        //                int stride = bmp_.BackBufferStride;

        //                bmpClone = bmp_.Clone();

        //                Task.Run(() =>
        //                {
        //                    OpenCvSharp.Mat localMat = null;

        //                    try
        //                    {
        //                        localMat = WriteableBitmapToMat(bmpClone, width, height, stride);

        //                        lock (_videoWriteingLock)
        //                        {
        //                            if (_videoWriter == null || !_videoWriter.IsOpened())
        //                            {
        //                                throw new InvalidOperationException("VideoWriter 未正确初始化或已关闭。");
        //                            }

        //                            _videoWriter.Write(localMat);
        //                        }
        //                    }
        //                    catch (Exception ex)
        //                    {
        //                        System.Windows.MessageBox.Show("Video writing error: " + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
        //                        System.Windows.MessageBox.Show("Stack Trace: " + ex.StackTrace, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
        //                    }
        //                    finally
        //                    {
        //                        if (localMat != null)
        //                        {
        //                            localMat.Dispose();
        //                        }
        //                    }
        //                });
        //            }

        //        }
        //        catch (Exception ex)
        //        {

        //            System.Windows.MessageBox.Show(ex.ToString());
        //        }

        //    }
        //}
        private void OnEventImage()
        {
            if (bmp_ != null)
            {
                try
                {
                    bmp_.Lock();
                    try
                    {
                        cam_.pull(bmp_.BackBuffer);/* Pull Mode */
                        bmp_.AddDirtyRect(new Int32Rect(0, 0, bmp_.PixelWidth, bmp_.PixelHeight));
                    }
                    finally
                    {
                        bmp_.Unlock();
                    }

                    if (showIF)
                    {
                        DrawIF(bmp_);
                    }

                    image_.Source = bmp_;

                    //if (_isRecording)
                    //{
                    //    int width = bmp_.PixelWidth;
                    //    int height = bmp_.PixelHeight;
                    //    int stride = bmp_.BackBufferStride;

                    //    bmpClone = bmp_.Clone();

                    //    Task.Run(() =>
                    //    {
                    //        OpenCvSharp.Mat localMat = null;

                    //        try
                    //        {
                    //            localMat = WriteableBitmapToMat(bmpClone, width, height, stride);

                    //            lock (_videoWriteingLock)
                    //            {
                    //                if (_videoWriter == null || !_videoWriter.IsOpened())
                    //                {
                    //                    throw new InvalidOperationException("VideoWriter 未正确初始化或已关闭。");
                    //                }

                    //                _videoWriter.Write(localMat);
                    //            }
                    //        }
                    //        catch (Exception ex)
                    //        {
                    //            System.Windows.MessageBox.Show("Video writing error: " + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    //            System.Windows.MessageBox.Show("Stack Trace: " + ex.StackTrace, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    //        }
                    //        finally
                    //        {
                    //            if (localMat != null)
                    //            {
                    //                localMat.Dispose();
                    //            }
                    //        }
                    //    });
                    //}


                }
                catch (Exception ex)
                {
                    System.Windows.MessageBox.Show(ex.ToString());
                }
            }
        }

        private OpenCvSharp.Mat WriteableBitmapToMat(WriteableBitmap writeableBitmap, int width, int height, int stride)
        {
            OpenCvSharp.Mat mat = new OpenCvSharp.Mat(height, width, OpenCvSharp.MatType.CV_8UC4);

            // 在 UI 线程中获取像素数据
            writeableBitmap.Dispatcher.Invoke(() =>
            {
                writeableBitmap.Lock();
                try
                {
                    IntPtr pBackBuffer = writeableBitmap.BackBuffer;
                    byte[] pixels = new byte[height * stride];
                    Marshal.Copy(pBackBuffer, pixels, 0, pixels.Length);
                    Marshal.Copy(pixels, 0, mat.Data, pixels.Length);
                }
                finally
                {
                    writeableBitmap.Unlock();
                }
            });

            return mat;
        }



        //private void SaveFrameForRecording(WriteableBitmap bmp)
        //{
        //    string _pathStr = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".bmp";

        //    //Dispatcher.BeginInvoke(new Action(() =>
        //    //{
        //        using (FileStream fileStream = new FileStream(_pathStr, FileMode.Create))
        //        {
        //            BitmapEncoder encoder = new BmpBitmapEncoder();
        //            encoder.Frames.Add(BitmapFrame.Create(bmp));
        //            encoder.Save(fileStream);
        //        }
        //    //}));
        //}


        private void SetPixel(WriteableBitmap wbm, int x, int y, System.Windows.Media.Color color)
        {
            if (x < 0 || x >= wbm.PixelWidth || y < 0 || y >= wbm.PixelHeight)
                return;

            wbm.Lock();
            try
            {
                IntPtr pBackBuffer = wbm.BackBuffer;
                pBackBuffer += y * wbm.BackBufferStride;
                pBackBuffer += x * 4;

                int colorData = color.R << 16; // R
                colorData |= color.G << 8;     // G
                colorData |= color.B << 0;     // B

                System.Runtime.InteropServices.Marshal.WriteInt32(pBackBuffer, colorData);
                wbm.AddDirtyRect(new Int32Rect(x, y, 1, 1));
            }
            finally
            {
                wbm.Unlock();
            }
        }


        private void DrawIF(WriteableBitmap bmp)
        {
            int centerX = bmp.PixelWidth / 2;
            int centerY = bmp.PixelHeight / 2;
            System.Windows.Media.Color IFColor = Colors.Green;
            System.Windows.Media.Color scaleColor = Colors.Green;

            int crosshairLength = Math.Min(bmp.PixelWidth, bmp.PixelHeight) / 1;
            int scaleInterval = 10;
            int scaleLength = 5;

            for (int x = centerX - crosshairLength; x <= centerX + crosshairLength; x++)
            {
                if (x >= 0 && x < bmp.PixelWidth)
                {
                    SetPixel(bmp, x, centerY, IFColor);
                    if ((x - centerX) % scaleInterval == 0)
                    {
                        for (int y = centerY - scaleLength; y <= centerY + scaleLength; y++)
                        {
                            if (y >= 0 && y < bmp.PixelHeight)
                            {
                                SetPixel(bmp, x, y, scaleColor);
                            }
                        }
                    }
                }
            }


            for (int y = centerY - crosshairLength; y <= centerY + crosshairLength; y++)
            {
                if (y >= 0 && y < bmp.PixelHeight)
                {
                    SetPixel(bmp, centerX, y, IFColor);
                    if ((y - centerY) % scaleInterval == 0)
                    {
                        for (int x = centerX - scaleLength; x <= centerX + scaleLength; x++)
                        {
                            if (x >= 0 && x < bmp.PixelWidth)
                            {
                                SetPixel(bmp, x, y, scaleColor);
                            }
                        }
                    }
                }
            }


        }


        private void IF_Checked(object sender, RoutedEventArgs e)
        {
            showIF = true;
            DrawIF(bmp_);
            image_.Source = bmp_;
        }

        private void IF_Unchecked(object sender, RoutedEventArgs e)
        {
            showIF = false;
            // 重新生成没有交叉线的位图并更新图像
            bmp_.Lock();
            try
            {
                cam_.pull(bmp_.BackBuffer);/* Pull Mode */
                bmp_.AddDirtyRect(new Int32Rect(0, 0, bmp_.PixelWidth, bmp_.PixelHeight));
            }
            finally
            {
                bmp_.Unlock();
            }
            image_.Source = bmp_;
        }







        private static void OnEventError()
        {
            cam_.close();
            cam_ = null;
            Marshal.FreeHGlobal(buf_);
            System.Windows.MessageBox.Show("Generic error");
        }

        private static void OnEventDisconnect()
        {
            cam_.close();
            cam_ = null;
            Marshal.FreeHGlobal(buf_);
            System.Windows.Application.Current.Dispatcher.Invoke(() => 
            {
                if (Common.languageCode == "zh-CN")
                {
                    MessageView messageView = new MessageView("摄像头断开", 0);
                    messageView.Owner = System.Windows.Application.Current.Windows.OfType<Window>().FirstOrDefault(w => w.IsActive);
                    messageView.ShowDialog();
                }
                else
                {
                    MessageView messageView = new MessageView("Camera Disconnected" , 0);
                    messageView.Owner = System.Windows.Application.Current.Windows.OfType<Window>().FirstOrDefault(w => w.IsActive);
                    messageView.ShowDialog();
                }
            });


        }

        private static void UpdateExpoTime()
        {
            int val = 0;
            cam_.get(uvcham.eCMD.EXPOTIME, out val);
            CommonData.ExpoSlider_value = val;
        }

        private static void UpdateAwb()
        {
            int val = 0;
            cam_.get(uvcham.eCMD.WBRED, out val);
            CommonData.R_value = val;
            cam_.get(uvcham.eCMD.WBGREEN, out val);
            CommonData.G_value = val;
            cam_.get(uvcham.eCMD.WBBLUE, out val);
            CommonData.B_value = val;
        }

        public static void stopCamera()
        {
            cam_?.close();
            cam_ = null;
            Marshal.FreeHGlobal(buf_);
        }

        private void MaxBtn_Click(object sender, RoutedEventArgs e)
        {
            if (!_maxed)
            {
                if (_fullScreenWindow == null)
                {
                    _fullScreenWindow = new System.Windows.Window();


                    WindowOperator.RemoveFromParent(this.testgrid, out _originalParent, out index);




                    _fullScreenWindow.Content = this.testgrid;
                    _fullScreenWindow.Background = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#6495ED"));
                    _fullScreenWindow.WindowStyle = WindowStyle.None;
                    _fullScreenWindow.WindowState = WindowState.Maximized;
                    _fullScreenWindow.ResizeMode = ResizeMode.NoResize;
                    _fullScreenWindow.Show();
                    _fullScreenWindow.Activate();
                    _maxed = true;
                }
            }
            else
            {
                var faSub = VisualTreeHelper.GetParent(this.testgrid);
                var loc = LogicalTreeHelper.GetParent(this.testgrid);
                RemoveChild(faSub, this.testgrid);
                RemoveChild(loc, this.testgrid);
                WindowOperator.AddToParent(this.testgrid, _originalParent, index);
                _fullScreenWindow.Close();
                _fullScreenWindow = null;
                _maxed = false;
            }
        }

        private void RemoveChild(DependencyObject parent, UIElement child)
        {
            var panel = parent as System.Windows.Controls.Panel;
            if (panel != null)
            {
                panel.Children.Remove(child);
                return;
            }
            var decorator = parent as Decorator;
            if (decorator != null)
            {
                if (decorator.Child == child)
                {
                    decorator.Child = null;
                }
                return;
            }
            var contentPresenter = parent as ContentPresenter;
            if (contentPresenter != null)
            {
                if (contentPresenter.Content == child)
                {
                    contentPresenter.Content = null;
                }
                return;
            }
            var contentControl = parent as ContentControl;
            if (contentControl != null)
            {
                if (contentControl.Content == child)
                {
                    contentControl.Content = null;
                }

                return;
            }
        }

        private void AddParent(DependencyObject parent, UIElement child)
        {
            if (parent is ContentControl contentControl)
                contentControl.Content = child;
        }

        public void RemoveChild2(Grid parent, UIElement child)
        {
            var grid = parent as Grid;
            if (grid != null)
            {
                if (grid.Children.Contains(child))
                {
                    grid.Children.Remove(child);
                }
            }
        }


        private void setBtn_Click(object sender, RoutedEventArgs e)
        {
            if (settingWindow == null)
            {
                settingWindow = new CameraSettingWindow();

                settingWindow.Owner = GetParentWindow(this);

                settingWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                settingWindow.ShowDialog();
            }

            if (settingWindow.DialogResult != true)
                settingWindow = null;
        }

        public void hideOrShowOtherButton()
        {
            List<System.Windows.Controls.Button> btnList = WindowOperator.FindVisualChild<System.Windows.Controls.Button>(this.operPanel);
            foreach (var item in btnList)
            {
                if (item != null)
                    if (item.Name != "MaxBtn")
                        if (item.Visibility != Visibility.Visible)
                            item.Visibility = Visibility.Visible;
                        else
                            item.Visibility = Visibility.Collapsed;
            }

            recordButton.Visibility = Visibility.Collapsed;
            photoButton.Visibility = Visibility.Visible;
            pho.Visibility = Visibility.Visible;
            pho.Content = "拍照模式";
            pho.Width = 143;
            rec.Content = "录像模式";
            rec.Width = 143;
            rec.Visibility = Visibility.Visible;
            setBtn.Visibility = Visibility.Visible;

            //reopen.Visibility = Visibility.Collapsed;


        }

        private void OpenFileWindow_uploadDelegate(object sender, ListControlModel e)
        {
            ListControlModel model = new ListControlModel { ImgPath = e.ImgPath, Name = e.Name };
            ScrollControl scrollControl = new ScrollControl();
            TextBlock textBlock = new TextBlock();
            textBlock.MinHeight = 1.5;
            scrollControl.DataContext = model;
            stackList.Children.Add(scrollControl);
            stackList.Children.Add(textBlock);
            if (util.isPatientSelected == true)
            {
                result.Id = pIdTxt.Text;
                result.Description = examResult.Text;
                result.Date = DateTime.Now;
                result.Path = model.ImgPath;
                result.Name = model.ImageName;
                service.SaveResults(result);
            }
        }

        private void InputBtn_Click(object sender, RoutedEventArgs e)
        {
            string content;
            //System.Windows.Forms.DialogResult res = System.Windows.Forms.MessageBox.Show("导入的图像可能不属于该病人，需要继续导入吗？", "确认", (System.Windows.Forms.MessageBoxButtons)MessageBoxButton.YesNo);

            if (Common.languageCode == "zh-CN")
            {
                content = "导入的图像可能不属于该病人，需要继续导入吗？";
            }
            else
            {
                content = "The imported meida may not belong to this patient,continue?";
            }

            MessageBoxResult result = MessageView.Show(content, "确认", MessageBoxButton.OKCancel);
            //MessageBoxResult result = System.Windows.MessageBox.Show("导入的图像可能不属于该病人，需要继续导入吗？", "确认", MessageBoxButton.OKCancel, MessageBoxImage.Information, MessageBoxResult.OK, System.Windows.MessageBoxOptions.DefaultDesktopOnly);
            System.Windows.Window window = System.Windows.Window.GetWindow(this);
            System.Windows.Point p = Mouse.GetPosition(this);
            //MessageBox m = new MessageBox("导入的图像可能不属于该病人，需要继续导入吗？", "确认", MessageBoxButton.OKCancel, MessageBoxImage.Information);


            if (result == MessageBoxResult.OK)
            {
                OpenFileWindow openFileWindow = new OpenFileWindow();
                openFileWindow.uploadDelegate += OpenFileWindow_uploadDelegate;
                openFileWindow.Topmost = true;
                openFileWindow.ShowDialog();

            }
        }

        private void camBtn_Click(object sender, RoutedEventArgs e)
        {
            if (t != null)
            {
                testgrid.Children.Remove(t);
            }
            if (CommonData.started_)
            {
                //int ret = uvcham.switcFlg;
                //CamaraView.cam_?.put(uvcham.eCMD.USER, (uvcham.switcFlg == 1) ? 0 : 1);
                //uvcham.switcFlg = (uvcham.switcFlg == 1 ? 0 : 1);
                if (switchFlg != 1)
                {
                    CameraView.cam_?.put(uvcham.eCMD.USER, 1);

                    CameraView.cam_?.put(uvcham.eCMD.WBRED, 50);
                    CameraView.cam_?.put(uvcham.eCMD.WBGREEN, 68);
                    CameraView.cam_?.put(uvcham.eCMD.WBBLUE, 328);

                    switchFlg = 1;
                }

                slider.Value = 0;
                slider2.Value = 0;

                // uvcham.switcFlg = (uvcham.switcFlg == 1 ? 0 : 1);

            }
            redStack.Visibility = Visibility.Collapsed;
            normalStack.Visibility = Visibility.Visible;
        }

        private void RedModeBtn_Click(object sender, RoutedEventArgs e)
        {
            if (t != null)
            {
                testgrid.Children.Remove(t);
            }
            if (CommonData.started_)
            {
                //int ret = uvcham.switcFlg;
                //CamaraView.cam_?.put(uvcham.eCMD.USER, (uvcham.switcFlg == 1) ? 0 : 1);
                //uvcham.switcFlg = (uvcham.switcFlg == 1 ? 0 : 1);
                if (switchFlg != 0)
                {
                    CameraView.cam_?.put(uvcham.eCMD.USER, 0);

                    CameraView.cam_?.put(uvcham.eCMD.WBRED, 158);
                    CameraView.cam_?.put(uvcham.eCMD.WBGREEN, 400);
                    CameraView.cam_?.put(uvcham.eCMD.WBBLUE, 331);

                    switchFlg = 0;
                }

                slider.Value = 0;
                slider2.Value = 0;

            }
            redStack.Visibility = Visibility.Visible;
            normalStack.Visibility = Visibility.Collapsed;
        }

        //private void slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        //{
        //    int intValue = Convert.ToInt32(slider.Value);
        //    if (intValue > 0)
        //    {
        //        Dispatcher.Invoke(new Action(() => { sliderTXT.Text = intValue.ToString().PadLeft(2, '0'); }));
        //    }
        //    else
        //    {
        //        Dispatcher.Invoke(new Action(() => { sliderTXT.Text = intValue.ToString(); }));
        //    }

        //    int crcValue = (4 + intValue) % 255;
        //    string hex = intValue.ToString("X").ToUpper().PadLeft(2, '0');
        //    string hex1 = crcValue.ToString("X").ToUpper().PadLeft(2, '0');
        //    string s = "FE040000" + hex + "00" + hex1 + "FF";
        //    byte[] buffer = ConvertHexStringToBytes(s);
        //    Thread.Sleep(100);
        //    SengInstructions(buffer);
        //}


        private async void slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            int intValue = Convert.ToInt32(slider.Value);

            if (intValue > 0)
            {
                sliderTXT.Text = intValue.ToString().PadLeft(2, '0');
            }
            else
            {
                sliderTXT.Text = intValue.ToString();
            }

            int crcValue = (4 + intValue) % 255;
            string hex = intValue.ToString("X").ToUpper().PadLeft(2, '0');
            string hex1 = crcValue.ToString("X").ToUpper().PadLeft(2, '0');
            string s = "FE040000" + hex + "00" + hex1 + "FF";
            byte[] buffer = ConvertHexStringToBytes(s);
            await Task.Delay(200);
            await Task.Run(() => SengInstructions(buffer));
        }



        private byte[] ConvertHexStringToBytes(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            byte[] returnBytes = new byte[hexString.Length / 2];
            if (hexString.Length % 2 == 0)
            {
                for (int i = 0; i < returnBytes.Length; i++)
                {
                    returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
                }
            }
            return returnBytes;
        }

        //private void slider2_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        //{
        //    int intValue = Convert.ToInt32(slider2.Value);
        //    if (intValue > 0)
        //    {
        //        Dispatcher.Invoke(new Action(() => { sliderTXT2.Text = intValue.ToString().PadLeft(2, '0'); }));
        //    }
        //    else
        //    {
        //        Dispatcher.Invoke(new Action(() => { sliderTXT2.Text = intValue.ToString(); }));
        //    }
        //    int crcValue = (5 + intValue) % 255;
        //    string hex = intValue.ToString("X").ToUpper().PadLeft(2, '0');
        //    string hex1 = crcValue.ToString("X").ToUpper().PadLeft(2, '0');
        //    string s = "FE040100" + hex + "00" + hex1 + "FF";
        //    byte[] buffer = ConvertHexStringToBytes(s);
        //    Thread.Sleep(200);
        //    SengInstructions(buffer);
        //}


        private async void slider2_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            int intValue = Convert.ToInt32(slider2.Value);
            if (intValue > 0)
            {
                sliderTXT2.Text = intValue.ToString().PadLeft(2, '0');
            }
            else
            {
                sliderTXT2.Text = intValue.ToString();
            }
            int crcValue = (5 + intValue) % 255;
            string hex = intValue.ToString("X").ToUpper().PadLeft(2, '0');
            string hex1 = crcValue.ToString("X").ToUpper().PadLeft(2, '0');
            string s = "FE040100" + hex + "00" + hex1 + "FF";
            byte[] buffer = ConvertHexStringToBytes(s);

            await Task.Delay(200);
            await Task.Run(() => SengInstructions(buffer));
        }



        private void ck1_Checked(object sender, RoutedEventArgs e)
        {
            slider.IsEnabled = false;
        }

        private void ck1_Unchecked(object sender, RoutedEventArgs e)
        {
            slider.IsEnabled = true;
        }

        private void ck2_Checked(object sender, RoutedEventArgs e)
        {
            slider2.IsEnabled = false;
        }

        private void ck2_Unchecked(object sender, RoutedEventArgs e)
        {
            slider2.IsEnabled = true;
        }

        private void BtnEdit_Click_1(object sender, RoutedEventArgs e)
        {
            Common.scrolllist = WindowOperator.GetChildObjects<ScrollControl>(stackList, typeof(ScrollControl));
            Common.isAddToNow = true;
            NewPatientView newPatientView = new NewPatientView();
            newPatientView.Owner = GetParentWindow(this);
            newPatientView.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            newPatientView.ShowDialog();
        }

        private void DelBtn_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Point scpoint = new System.Windows.Point();
            string path = string.Empty;
            ScrollControl sc = new ScrollControl();
            ListControlModel p = new ListControlModel();
            VideoModel video = new VideoModel();
            List<ScrollControl> lits = WindowOperator.GetChildObjects<ScrollControl>(stackList, typeof(ScrollControl));
            if (lits.Count > 0)
            {
                for (int i = 0; i < lits.Count; i++)
                {
                    sc = (ScrollControl)lits[i];

                    if (sc.IsMyChecked)
                    {
                        ///path = sc.DataContext;
                        p = sc.DataContext as ListControlModel;
                        //path = sc.DataContext

                        try
                        {
                            if (util.isPatientSelected)
                            {
                                if (p != null)
                                {

                                    if (picEditView != null)
                                    {
                                        p = picEditView.DataContext as ListControlModel;
                                        string s = p.ImgPath;

                                        if (s == path)
                                        {
                                            picEditView.Close();
                                        }
                                    }

                                    if (service.DeletePic(p.ImgPath, pIdTxt.Text))
                                    {
                                        stackList.Children.Remove(sc);
                                    }


                                    //p = picEditView.DataContext as ListControlModel;
                                    //string s = p.ImgPath;

                                    //if (s == path)
                                    //{
                                    //    picEditView.Close();
                                    //}
                                    //File.Delete(path);
                                }
                                else
                                {
                                    VideoModel videoModel = sc.DataContext as VideoModel;
                                    if (videoModel != null)
                                    {
                                        if (service.DeletePic(videoModel.VideoPath, pIdTxt.Text))
                                        {
                                            stackList.Children.Remove(sc);
                                        }
                                    }

                                }
                            }
                            else
                            {
                                stackList.Children.Remove(sc);
                            }

                        }
                        catch { }
                        finally
                        {

                        }


                    }
                }
                sc = lits[0];
                sc.IsMyChecked = true;

                allCheck.IsChecked = false;

            }






        }

        private void allCheck_Checked(object sender, RoutedEventArgs e)
        {
            ScrollControl sc = new ScrollControl();
            List<ScrollControl> lits = WindowOperator.GetChildObjects<ScrollControl>(stackList, typeof(ScrollControl));
            System.Windows.Controls.CheckBox ck = sender as System.Windows.Controls.CheckBox;
            if (ck.IsChecked == true)
            {
                if (lits.Count > 0)
                {
                    for (int i = 0; i < lits.Count; i++)
                    {
                        sc = (ScrollControl)lits[i];
                        sc.myCheckBox.IsChecked = true;
                        sc.IsMyChecked = true;
                    }
                }
            }
            else
            {
                if (lits.Count > 0)
                {
                    for (int i = 0; i < lits.Count; i++)
                    {
                        sc = (ScrollControl)lits[i];
                        sc.myCheckBox.IsChecked = false;
                        sc.IsMyChecked = false;
                    }
                }
            }
        }

        private void allCheck_Unchecked(object sender, RoutedEventArgs e)
        {
            ScrollControl sc = new ScrollControl();
            List<ScrollControl> lits = WindowOperator.GetChildObjects<ScrollControl>(stackList, typeof(ScrollControl));
            System.Windows.Controls.CheckBox ck = sender as System.Windows.Controls.CheckBox;
            if (ck.IsChecked == true)
            {
                if (lits.Count > 0)
                {
                    for (int i = 0; i < lits.Count; i++)
                    {
                        sc = (ScrollControl)lits[i];
                        sc.myCheckBox.IsChecked = true;
                        sc.IsMyChecked = true;
                    }
                }
            }
            else
            {
                if (lits.Count > 0)
                {
                    for (int i = 0; i < lits.Count; i++)
                    {
                        sc = (ScrollControl)lits[i];
                        sc.myCheckBox.IsChecked = false;
                        sc.IsMyChecked = false;
                    }
                }
            }

        }

        private void OutputBtn_Click(object sender, RoutedEventArgs e)
        {

        }


        private BitmapEncoder GetEncoder(int filterIndex)
        {
            switch (filterIndex)
            {
                case 1: return new JpegBitmapEncoder();
                case 2: return new PngBitmapEncoder();
                case 3: return new BmpBitmapEncoder();
                default: throw new NotSupportedException("不支持的图片格式。");
            }
        }


        //private void OutputBtn_Click_1(object sender, RoutedEventArgs e)
        //{
        //    List<string> selectedImagePaths = new List<string>();

        //    foreach (var child in stackList.Children)
        //    {
        //        if (child is ScrollControl scrollControl)
        //        {
        //            if (scrollControl.IsMyChecked == true)
        //            {
        //                ListControlModel model = scrollControl.DataContext as ListControlModel;
        //                if (model != null && !string.IsNullOrEmpty(model.ImgPath))
        //                {
        //                    selectedImagePaths.Add(model.ImgPath);
        //                }
        //            }
        //        }
        //    }

        //    if (selectedImagePaths.Any())
        //    {
        //        SaveFileDialog saveFileDialog = new SaveFileDialog();
        //        saveFileDialog.Title = "请选择导出目录并输入文件名";
        //        saveFileDialog.Filter = "JPEG 图像|*.jpg|PNG 图像|*.png|BMP 图像|*.bmp"; 
        //        saveFileDialog.AddExtension = true;
        //        saveFileDialog.CheckPathExists = true;
        //        saveFileDialog.OverwritePrompt = true;
        //        saveFileDialog.FileName = DateTime.Now.ToString("yyyyMMdd_HHmmss") ;

        //        if (saveFileDialog.ShowDialog() == true)
        //        {
        //            string exportFilePath = saveFileDialog.FileName;

        //            foreach (var ImagePath in selectedImagePaths)
        //            {
        //                try
        //                {
        //                    BitmapImage bitmapImage = new BitmapImage(new Uri(ImagePath));
        //                    var encoder = GetEncoder(saveFileDialog.FilterIndex);

        //                    using (var ms = new MemoryStream())
        //                    {
        //                        encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
        //                        encoder.Save(ms);

        //                        using (var fs = new FileStream(exportFilePath, FileMode.Create))
        //                        {
        //                            ms.WriteTo(fs);
        //                        }

        //                        Console.WriteLine($"成功导出图片至: {exportFilePath}");
        //                    }
        //                }
        //                catch (Exception ex)
        //                {
        //                    Console.WriteLine($"导出图片时发生错误: {ex.Message}");
        //                }
        //            }
        //            Console.WriteLine("图片导出完成。");
        //        }
        //        else
        //        {
        //            Console.WriteLine("导出操作被取消。");
        //        }
        //    }
        //    else
        //    {
        //        Console.WriteLine("没有图片被选中进行导出。");
        //    }

        //}

        //private void OutputBtn_Click_1(object sender, RoutedEventArgs e)
        //{
        //    List<string> selectedImagePaths = new List<string>();

        //    foreach (var child in stackList.Children)
        //    {
        //        if (child is ScrollControl scrollControl)
        //        {
        //            if (scrollControl.IsMyChecked == true)
        //            {
        //                ListControlModel model = scrollControl.DataContext as ListControlModel;
        //                if (model != null && !string.IsNullOrEmpty(model.ImgPath))
        //                {
        //                    selectedImagePaths.Add(model.ImgPath);
        //                }
        //            }
        //        }
        //    }

        //    if (selectedImagePaths.Any())
        //    {
        //        SaveFileDialog saveFileDialog = new SaveFileDialog();
        //        saveFileDialog.Title = "请选择导出目录并输入文件名";
        //        saveFileDialog.Filter = "JPEG 图像|*.jpg|PNG 图像|*.png|BMP 图像|*.bmp";
        //        saveFileDialog.AddExtension = true; // 确保自动添加正确的文件扩展名
        //        saveFileDialog.CheckPathExists = true;
        //        saveFileDialog.OverwritePrompt = true;

        //        // 移动到循环外，用户只需选择一次导出位置和文件名
        //        if (saveFileDialog.ShowDialog() == true)
        //        {
        //            string baseExportFilePath = saveFileDialog.FileName;
        //            int fileIndex = 1; // 用于处理同名文件的情况

        //            foreach (var imagePath in selectedImagePaths)
        //            {
        //                try
        //                {
        //                    BitmapImage bitmapImage = new BitmapImage(new Uri(imagePath));
        //                    var encoder = GetEncoder(saveFileDialog.FilterIndex);

        //                    string uniqueFilePath = baseExportFilePath;
        //                    // 如果用户未在文件名后指定扩展名，这里确保添加正确的扩展名
        //                    if (!System.IO.Path.HasExtension(uniqueFilePath))
        //                    {
        //                        uniqueFilePath += saveFileDialog.Filter.Split('|')[saveFileDialog.FilterIndex].Split('.')[1];
        //                    }

        //                    // 处理同名文件冲突
        //                    while (File.Exists(uniqueFilePath))
        //                    {
        //                        string fileNameWithoutExt = Path.GetFileNameWithoutExtension(uniqueFilePath);
        //                        string ext = System.IO.Path.GetExtension(uniqueFilePath);
        //                        uniqueFilePath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(baseExportFilePath), $"{fileNameWithoutExt}_{fileIndex}{ext}");
        //                        fileIndex++;
        //                    }

        //                    using (var ms = new MemoryStream())
        //                    {
        //                        encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
        //                        encoder.Save(ms);

        //                        using (var fs = new FileStream(uniqueFilePath, FileMode.Create))
        //                        {
        //                            ms.WriteTo(fs);
        //                        }

        //                        Console.WriteLine($"成功导出图片至: {uniqueFilePath}");
        //                    }
        //                }
        //                catch (Exception ex)
        //                {
        //                    Console.WriteLine($"导出图片时发生错误: {ex.Message}");
        //                }
        //            }
        //            Console.WriteLine("所有图片导出完成。");
        //        }
        //        else
        //        {
        //            Console.WriteLine("导出操作被取消。");
        //        }
        //    }
        //    else
        //    {
        //        Console.WriteLine("没有图片被选中进行导出。");
        //    }
        //}
        public List<string> selectedImagePaths = new List<string>();



        //private void OutputBtn_Click_1(object sender, RoutedEventArgs e)
        //{

        //    foreach (var child in stackList.Children)
        //    {
        //        if (child is ScrollControl scrollControl)
        //        {
        //            ListControlModel model = scrollControl.DataContext as ListControlModel;

        //            if (scrollControl.IsMyChecked == true)
        //            {
        //                if (model != null && !string.IsNullOrEmpty(model.ImgPath))
        //                {
        //                    selectedImagePaths.Add(model.ImgPath);
        //                }
        //            }

        //        }
        //    }

        //    if (selectedImagePaths.Any())
        //    {
        //        SaveFileDialog saveFileDialog = new SaveFileDialog();
        //        saveFileDialog.Title = "请选择导出目录并输入文件名";
        //        saveFileDialog.Filter = "JPEG 图像|*.jpg|PNG 图像|*.png|BMP 图像|*.bmp";
        //        saveFileDialog.AddExtension = true; // 确保自动添加正确的文件扩展名
        //        saveFileDialog.CheckPathExists = true;
        //        saveFileDialog.OverwritePrompt = true;

        //        // 移动到循环外，用户只需选择一次导出位置和文件名
        //        if (saveFileDialog.ShowDialog() == true)
        //        {
        //            string baseExportFilePath = saveFileDialog.FileName;
        //            int fileIndex = 1; // 用于处理同名文件的情况

        //            foreach (var imagePath in selectedImagePaths)
        //            {
        //                try
        //                {
        //                    BitmapImage bitmapImage = new BitmapImage(new Uri(imagePath));
        //                    var encoder = GetEncoder(saveFileDialog.FilterIndex);

        //                    string uniqueFilePath = baseExportFilePath;
        //                    // 如果用户未在文件名后指定扩展名，这里确保添加正确的扩展名
        //                    if (!System.IO.Path.HasExtension(uniqueFilePath))
        //                    {
        //                        uniqueFilePath += saveFileDialog.Filter.Split('|')[saveFileDialog.FilterIndex].Split('.')[1];
        //                    }

        //                    // 处理同名文件冲突
        //                    while (File.Exists(uniqueFilePath))
        //                    {
        //                        string fileNameWithoutExt = System.IO.Path.GetFileNameWithoutExtension(uniqueFilePath);
        //                        string ext = System.IO.Path.GetExtension(uniqueFilePath);
        //                        uniqueFilePath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(baseExportFilePath), $"{fileNameWithoutExt}_{fileIndex}{ext}");
        //                        fileIndex++;
        //                    }

        //                    using (var ms = new MemoryStream())
        //                    {
        //                        encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
        //                        encoder.Save(ms);

        //                        using (var fs = new FileStream(uniqueFilePath, FileMode.Create))
        //                        {
        //                            ms.WriteTo(fs);
        //                        }

        //                        Console.WriteLine($"成功导出图片至: {uniqueFilePath}");
        //                    }
        //                }
        //                catch (Exception ex)
        //                {
        //                    Console.WriteLine($"导出图片时发生错误: {ex.Message}");
        //                }
        //            }
        //            Console.WriteLine("所有图片导出完成。");

        //        }
        //        else
        //        {
        //            Console.WriteLine("导出操作被取消。");
        //        }

        //        selectedImagePaths.Clear(); 

        //    }
        //    else
        //    {
        //        Console.WriteLine("没有图片被选中进行导出。");
        //    }




        //}


        private void OutputBtn_Click_1(object sender, RoutedEventArgs e)
        {

            foreach (var child in stackList.Children)
            {
                if (child is ScrollControl scrollControl && scrollControl.IsMyChecked)
                {
                    var dataContext = scrollControl.DataContext;

                    if (dataContext is ListControlModel imageModel && !string.IsNullOrEmpty(imageModel.ImgPath))
                    {
                        selectedImagePaths.Add(imageModel.ImgPath);
                    }
                    else if (dataContext is VideoModel videoModel && !string.IsNullOrEmpty(videoModel.VideoPath))
                    {
                        selectedImagePaths.Add(videoModel.VideoPath);
                    }

                }
            }

            if (selectedImagePaths.Any())
            {
                Microsoft.Win32.SaveFileDialog saveFileDialog = new Microsoft.Win32.SaveFileDialog();
                saveFileDialog.Title = "请选择导出目录并输入文件名";
                saveFileDialog.Filter = "JPEG 图像|*.jpg|PNG 图像|*.png|BMP 图像|*.bmp|AVI 视频|*.avi|MP4 视频|*.mp4";
                saveFileDialog.AddExtension = true; // 确保自动添加正确的文件扩展名
                saveFileDialog.CheckPathExists = true;
                saveFileDialog.OverwritePrompt = true;

                if (saveFileDialog.ShowDialog() == true)
                {
                    string baseExportFilePath = saveFileDialog.FileName;
                    int fileIndex = 1;
                    string[] filters = saveFileDialog.Filter.Split('|');
                    string targetExtension = filters[(saveFileDialog.FilterIndex - 1) * 2 + 1].Split('.')[1];

                    foreach (var filePath in selectedImagePaths)
                    {
                        string uniqueFilePath = EnsureUniqueFilePath(baseExportFilePath, fileIndex, targetExtension);

                        try
                        {
                            // 使用BitmapDecoder读取原始图片
                            var decoder = BitmapDecoder.Create(new Uri(filePath), BitmapCreateOptions.None, BitmapCacheOption.Default);
                            {
                                // 使用BitmapEncoder创建目标格式的图像
                                BitmapEncoder encoder;
                                switch (targetExtension)
                                {
                                    case "jpg":
                                        encoder = new JpegBitmapEncoder();
                                        break;
                                    case "png":
                                        encoder = new PngBitmapEncoder();
                                        break;
                                    case "bmp":
                                        encoder = new BmpBitmapEncoder();
                                        break;
                                    // 添加其他格式的支持
                                    default:
                                        throw new NotSupportedException($"Unsupported image format: {targetExtension}");
                                }

                                // 将解码后的帧添加到编码器
                                foreach (BitmapFrame frame in decoder.Frames)
                                {
                                    encoder.Frames.Add(frame);
                                }

                                // 保存到新路径
                                using (var stream = new FileStream(uniqueFilePath, FileMode.Create))
                                {
                                    encoder.Save(stream);
                                }
                            }

                            Console.WriteLine($"成功导出文件至: {uniqueFilePath}");
                            fileIndex++; // 增加文件索引以处理同名文件
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"导出图片时发生错误: {ex.Message}");
                        }
                    }

                    Console.WriteLine("所有图片导出完成。");
                }
                else
                {
                    Console.WriteLine("导出操作被取消。");
                }

                selectedImagePaths.Clear();

            }
            else
            {
                Console.WriteLine("没有图片被选中进行导出。");
            }




        }



        private static string EnsureUniqueFilePath(string baseFilePath, int fileIndex, string fileExtension)
        {
            string fileNameWithoutExt = System.IO.Path.GetFileNameWithoutExtension(baseFilePath);
            string directoryPath = System.IO.Path.GetDirectoryName(baseFilePath);
            string uniqueFilePath = System.IO.Path.Combine(directoryPath, $"{fileNameWithoutExt}_{fileIndex}.{fileExtension}");

            // 检查文件是否已存在，如果存在则递增索引并重试
            while (System.IO.File.Exists(uniqueFilePath))
            {
                fileIndex++;
                uniqueFilePath = System.IO.Path.Combine(directoryPath, $"{fileNameWithoutExt}_{fileIndex}.{fileExtension}");
            }

            return uniqueFilePath;
        }



        public void RadioButton_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Controls.RadioButton radioButton = sender as System.Windows.Controls.RadioButton;

            if (radioButton == pho)
            {
                photoButton.Visibility = Visibility.Visible;
                recordButton.Visibility = Visibility.Hidden;
                recordTime.Visibility = Visibility.Hidden;
            }
            else if (radioButton == rec)
            {
                photoButton.Visibility = Visibility.Hidden;
                recordButton.Visibility = Visibility.Visible;
                recordTime.Visibility = Visibility.Visible;

            }
        }


        private void reopen_Click(object sender, RoutedEventArgs e)
        {
            if (cam_ == null)
            {
                openCamera();
                //if (cam_ != null) reopen.Visibility = Visibility.Collapsed;
            }
        }

        //private void lBtn_Click(object sender, RoutedEventArgs e)
        //{
        //    if (cam_ != null)
        //    {
        //        if ((string)lBtn.Content == "Record")
        //        {
        //            Microsoft.Win32.SaveFileDialog dialog = new Microsoft.Win32.SaveFileDialog();
        //            dialog.Filter = "ASF File|*.asf|MP4 File|*.mp4|MKV File|*.mkv";
        //            bool? result = dialog.ShowDialog();
        //            if (result == true)
        //            {
        //                try
        //                {
        //                    cam_.record(dialog.FileName);
        //                }
        //                catch (Exception ex)
        //                {


        //                    System.Windows.MessageBox.Show(ex.ToString());

        //                }
        //                lBtn.Content = "Stop";
        //            }
        //        }
        //        else
        //        {
        //            cam_.record(null);
        //            lBtn.Content = "Record";
        //        }
        //    }
        //}





        //private void Onstart()
        //{
        //    if (cam2_ != null) return;

        //    uvcham.Device[] arr2 = uvcham.Enum();

        //    if (arr2.Length <= 0) System.Windows.MessageBox.Show("No camera found.");
        //    if (cam2_ != null)
        //    {
        //        //cam2_.put(uvcham.eCMD.FORMAT, 1);
        //        CommonData.Expo_enabled = true;
        //        CommonData.balance_enabled = true;
        //        int width = 0, height = 0, res = 0;
        //        cam2_.get(uvcham.eCMD.RES, out res);
        //        cam2_.get(uvcham.eCMD.WIDTH | ((uvcham.eCMD)res), out width);
        //        cam2_.get(uvcham.eCMD.HEIGHT | ((uvcham.eCMD)res), out height);
        //        //height += 40;
        //        bmp2_ = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
        //        if ((width > 0) && (height > 0))
        //        {
        //            buf2_ = Marshal.AllocHGlobal(uvcham.TDIBWIDTHBYTES(width * 32) * height);
        //            if (cam2_.start(buf2_, (nEvent) =>
        //            {
        //                Dispatcher.BeginInvoke((Action)(() =>
        //                {
        //                    if (cam2_ != null)
        //                    {
        //                        if ((nEvent & uvcham.eEVENT.IMAGE) != 0)
        //                        {
        //                            if (bmp2_ != null)
        //                            {
        //                                try
        //                                {
        //                                    bmp_.Lock();
        //                                    try
        //                                    {
        //                                        cam_.pull(bmp2_.BackBuffer);/* Pull Mode */
        //                                        bmp_.AddDirtyRect(new Int32Rect(0, 0, bmp_.PixelWidth, bmp_.PixelHeight));
        //                                    }
        //                                    finally
        //                                    {
        //                                        bmp_.Unlock();
        //                                    }
        //                                    image_.Source = bmp_;

        //                                    BitmapSource bmp2source = ConvertBitmapToBitmapSource(bmp2_);

        //                                    image_.Source = bmp2source;

        //                                    Bitmap bmpClone = (Bitmap)bmp2_.Clone();

        //                                    if (_isRecording)
        //                                    {
        //                                        Task.Run(() =>
        //                                        {


        //                                            OpenCvSharp.Mat localMat = BitmapConverter.ToMat(bmpClone);

        //                                            lock (_videoWriteingLock)
        //                                            {
        //                                                _videoWriter?.Write(localMat);
        //                                            }

        //                                            localMat.Dispose();
        //                                            bmpClone.Dispose();
        //                                        });
        //                                    }


        //                                }
        //                                catch (Exception ex)
        //                                {
        //                                    System.Windows.MessageBox.Show(ex.ToString());
        //                                }
        //                            }
        //                        }

        //                        else if ((nEvent & uvcham.eEVENT.ERROR) != 0)
        //                            OnEventError();
        //                        else if ((nEvent & uvcham.eEVENT.DISCONNECT) != 0)
        //                            OnEventDisconnect();


        //                    }
        //                }));
        //            }) < 0)
        //            {
        //                System.Windows.MessageBox.Show("相机启动失败");
        //            }
        //            else
        //            {
        //                int nmin, nmax, ndef;
        //                cam2_.range(uvcham.eCMD.EXPOTIME, out nmin, out nmax, out ndef);
        //                CommonData.ExpoSlider_Max = nmax;
        //                CommonData.ExpoSlider_Min = nmin;
        //                cam2_.range(uvcham.eCMD.WBRED, out nmin, out nmax, out ndef);
        //                CommonData.R_Max = nmax;
        //                CommonData.R_Min = nmin;
        //                cam2_.range(uvcham.eCMD.WBGREEN, out nmin, out nmax, out ndef);
        //                CommonData.G_Max = nmax;
        //                CommonData.G_Min = nmin;
        //                cam2_.range(uvcham.eCMD.WBBLUE, out nmin, out nmax, out ndef);
        //                CommonData.B_Max = nmax;
        //                CommonData.B_Min = nmin;
        //                UpdateExpoTime();
        //                UpdateAwb();
        //                int val = 0;
        //                cam2_.get(uvcham.eCMD.AEXPO, out val);
        //                CommonData.Expo_checked = (1 == val);
        //                CommonData.ExpoSlider_enabled = (1 != val);
        //                cam2_.get(uvcham.eCMD.WBMODE, out val);
        //                CommonData.Expo_checked = (1 == val);
        //                CommonData.R_enabled = (1 != val);
        //                CommonData.G_enabled = (1 != val);
        //                CommonData.B_enabled = (1 != val);
        //                timer_ = new DispatcherTimer() { Interval = new TimeSpan(0, 0, 1) };
        //                timer_.Tick += (object sender, EventArgs e) =>
        //                {
        //                    if (cam2_ != null)
        //                    {
        //                        if (CommonData.Expo_checked)
        //                            UpdateExpoTime();
        //                        if (CommonData.balance_checked)
        //                            UpdateAwb();
        //                    }
        //                };
        //                timer_.Start();
        //            }
        //            CommonData.started_ = true;
        //        }
        //    }
        //}



        //public BitmapSource ConvertBitmapToBitmapSource(Bitmap bitmap)
        //{
        //    IntPtr hBitmap = bitmap.GetHbitmap();
        //    BitmapSource bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(
        //        hBitmap,
        //        IntPtr.Zero,
        //        Int32Rect.Empty,
        //        BitmapSizeOptions.FromEmptyOptions());

        //    // 删除 GDI 对象以释放资源
        //    DeleteObject(hBitmap);

        //    return bitmapSource;
        //}

        //[System.Runtime.InteropServices.DllImport("gdi32.dll")]
        //public static extern bool DeleteObject(IntPtr hObject);



        private void Slider_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            Slider slider = sender as Slider;
            System.Windows.Point position = e.GetPosition(slider);

            double relativePosition = position.X / slider.ActualWidth;
            double newValue = slider.Minimum + (relativePosition * (slider.Maximum - slider.Minimum));

            slider.Value = newValue;
        }

        private static System.Windows.Window GetParentWindow(DependencyObject child)
        {
            DependencyObject parent = VisualTreeHelper.GetParent(child);

            if (parent == null) return null;

            if (parent is System.Windows.Window) return (System.Windows.Window)parent;
            else return GetParentWindow(parent);
        }


        private void RecordTimer_Tick(object sender, EventArgs e)
        {
            _recordingTime = _recordingTime.Add(TimeSpan.FromSeconds(1));
            recordTime.Text = _recordingTime.ToString(@"hh\:mm\:ss");
        }


        private void VideoPlayerWindow_cutDelegate(object sender, ScrollControl e)
        {
            ScrollControl scrollControl = new ScrollControl();
            scrollControl = e;
            if (scrollControl != null)
            {
                stackList.Children.Add(scrollControl);
            }
        }


        private void ScrollControl_videoDelegate(object sender, VideoModel e)
        {
            VideoModel videoModel = new VideoModel();
            videoModel = e as VideoModel;
            if (picEditView == null)
            {
                VideoPlayerWindow videoPlayerWindow = new VideoPlayerWindow(videoModel.VideoPath);
                videoPlayerWindow.Owner = GetParentWindow(this);
                videoPlayerWindow.Left = Common.picpostion.X + 8;
                videoPlayerWindow.Top = Common.picpostion.Y + 218;
                videoPlayerWindow.ShowDialog();
            }


        }

        private void PicEditView_imgprocessDelegate(object sender, ListControlModel e)
        {
            ListControlModel listControlModel = new ListControlModel();
            listControlModel = e as ListControlModel;

            ScrollControl scrollControl = new ScrollControl();
            scrollControl.DataContext = listControlModel;
            stackList.Children.Add(scrollControl);

            if (util.isPatientSelected == true)
            {
                result.Id = pIdTxt.Text;
                result.Description = examResult.Text;
                result.Date = DateTime.Now;
                result.Path = listControlModel.ImgPath;
                result.Name = listControlModel.Name;
                service.SaveResults(result);
            }

        }
        

        private void adminControl_Click(object sender, RoutedEventArgs e)
        {
            AdminView adminView = new AdminView();
            adminView.Owner = GetParentWindow(this);
            adminView.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            adminView.ShowDialog();

        }

        private void AdminView_adminDelegate(object sender , bool isAdmin)
        {
            bool _isAdmin = isAdmin;
            if (_isAdmin)
            {
                adminControl.Foreground = System.Windows.Media.Brushes.Red;
                adminControl.Opacity = 1;
                Common.isAdminMode = true;
                IFCheck.Visibility = Visibility.Visible;
            }
            if (!_isAdmin)
            {
                adminControl.Foreground = System.Windows.Media.Brushes.Transparent;
                adminControl.Opacity = 0;
                Common.isAdminMode = false;
                IFCheck.Visibility = Visibility.Collapsed;
            }

        }


    }


    public class SerialPortEventArgs : EventArgs
    {
        public byte[] receivedBytes = null;   // 用来接收串口读取的数据
    }



}
